<template>
  <div>
    <el-form :model="productInfos" ref="productInfos" label-width="120px">
      <fieldset style="border: none;padding: 0;border-top: 1px solid #eee; margin-bottom: 20px;">
        <legend>
          <a name="hr">{{productInfos.productsName}}</a>
        </legend>
      </fieldset>
      <el-row>
        <el-col :span="24">
          <el-form-item
            v-for="(productInfo, index) in productInfos.products"
            :label="productInfo.productName+'：'"
            :key="productInfo.productSort">
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="库存："
                  :prop="'products.'+index+'.productNumber'"
                  :rules="{ required: true, validator: productNumberRule, trigger: 'blur' }">
                  <el-input v-model="productInfo.productNumber" @change="productNumberChange"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="警报库存："
                  :prop="'products.'+index+'.productWarnNumber'"
                  :rules="{ required: true, validator: productWarnNumberRule, trigger: 'blur' }">
                  <el-input v-model="productInfo.productWarnNumber"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="溢价："
                  :prop="'products.'+index+'.productPrice'"
                  :rules="{ required: true, validator: productPriceRule, trigger: 'blur' }">
                  <el-input v-model="productInfo.productPrice"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-row>
              <el-col :span="8">
                <el-form-item label="总库存">
                  <el-input v-model="productAllNumber" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="blackGoodsList"><i class="el-icon-back el-icon--left"></i>返回</el-button>
        <el-button type="primary" @click="submitProducts('productInfos')"><i class="el-icon-upload2 el-icon--left"></i>保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import forSaleApi from '@/api/backstage/forSale'
  export default {
    name: 'GoodsInfo',
    props:['message'],
    data() {
      return {
        /** 库存信息 **/
        productInfos:{},
        /** 总库存 **/
        productAllNumber:0,
        productOfGoodsInfo:{},
      }
    },
    created(){
      this.initPage();
    },
    methods: {
      initPage(){
        this.productOfGoodsInfo.id = this.message.id;
        let params = {
          goodsId:this.message.id,
          catId:this.message.catId
        }
        forSaleApi.initProducts({id: params.goodsId, catId: params.catId}).then(res => {
          this.productInfos = res.data;
          this.productAllNumber = res.data.productAllNumber;
        }).catch(() => {
          this.$message.error("商品库存信息获取失败");
        })
      },
      productNumberRule(rule, value, callback){
        /** 库存数据规则校验 **/
        if (value === '') {
          callback(new Error('请输库存数据'));
        }
        if(!(/^(?:[0-9]{1,7}|100000)$/.test(value))){
          callback(new Error('范围（1~10000000）'));
        }
        callback();
      },
      productWarnNumberRule(rule, value, callback){
        /** 库存警报数据规则校验 **/
        if (value === '') {
          callback(new Error('请输库存警报数据'));
        }
        if(!(/^(?:[0-9]{1,7}|100000)$/.test(value))){
          callback(new Error('范围（1~10000000）'));
        }
        callback();
      },
      productPriceRule(rule, value, callback){
        /** 商品尺寸溢价 **/
        if (value === ''){
          callback("请输入商品该尺寸溢价");
        } else {
          let marketPriceRegex = /^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$/
          if (!marketPriceRegex.test(value)){
            callback(new Error('范围（0.00~9999999.99）'));
          }
        }
        callback();
      },
      productNumberChange(value){
        /** 总库存实时跟新 **/
        this.productAllNumber = 0;
        this.productInfos.products.forEach((product, index) => {
          if((/^(?:[0-9]{1,7}|100000)$/.test(product.productNumber))){
            this.productAllNumber = parseInt(this.productAllNumber)+parseInt(product.productNumber);
          }
        });
      },
      blackGoodsList(){
        this.$emit('productInfoBackClick');
      },
      submitProducts(productsName){
        this.$refs[productsName].validate(valid => {
          if (valid) {
            this.productOfGoodsInfo.goodsNumber = this.productAllNumber;
            let params = {
              products: JSON.parse(JSON.stringify(this.productInfos.products)),
              goodsInfo: JSON.parse(JSON.stringify(this.productOfGoodsInfo)),
            }
            forSaleApi.saveProductsInfos(params).then(res => {
              this.$notify.success({title:'成功', message:'修改库存成功！'});
              /** 提交成功后返回列表页 **/
              this.$emit('productInfoSubmit');
            }).catch(() => {
              this.$notify.error({title:'失败', message:'库存信息提交失败，请稍后再试！'});
            });
            console.log(params);
          } else {
            /** 基本信息不合规 **/
            this.$notify.warning({title:'提示', message:'库存信息存在不合规！'});
            return false
          }
        })
      }
    }
  }
</script>
<style>
</style>
